﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.CodeAnalysis.Differencing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using SRM.Core.Extension;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Utility;
using SRM.WebSite.Models.Account;

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SRM.WebSite.Controllers
{
   
    public class AccountController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly ILogger<AccountController> _logger;

        public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<AccountController> logger, RoleManager<IdentityRole> roleManager)
        {
            this._userManager = userManager;
            this._signInManager = signInManager;
            this._logger = logger;
            _roleManager = roleManager;
        }

        [AllowAnonymous]
        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Login(LoginViewModel viewModel)
        {
            _logger.Log(LogLevel.Warning, "用户登录");
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByNameAsync(viewModel.UserName);
                if (user == null)
                {
                    ModelState.AddModelError("用户登录", $"用户名{viewModel.UserName}不存在");
                    return View(viewModel);
                }

                var result = await _signInManager.PasswordSignInAsync(user, viewModel.Password, viewModel.Rememberme, true);

                if (result.Succeeded)
                {
                    LoginUser.LoginUsers.SupplierId = user.Id;
                    LoginUser.LoginUsers.SupplierName = user.SupplierName;
                    LoginUser.LoginUsers.SupplierNo = user.SupplierNo;
                    LoginUser.LoginUsers.UserName = user.UserName;

                    return RedirectToAction("Index", "PurchaseOrder");
                }

                if (result.IsLockedOut)
                {
                    return View(nameof(AccountLocked), viewModel.UserName);
                }
                ModelState.AddModelError("", "登录失败，请重试");
            }
            return View(viewModel);
        }


        [AllowAnonymous]
        public IActionResult AccountLocked(string userName)
        {
            return View(nameof(AccountLocked), userName);
        }

        [AllowAnonymous]
        public async Task<IActionResult> Appeal(string userName)
        {
            var user = await _userManager.FindByNameAsync(userName);
            if (user != null)
            {
                //重置密码
                //var token = await _userManager.GeneratePasswordResetTokenAsync(user);
                //var result = await _userManager.ResetPasswordAsync(user, token, "123456");
                //if (result.Succeeded)
                //{
                if (await _userManager.IsLockedOutAsync(user))
                {
                    await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.UtcNow);
                }
                //}
            }
            return RedirectToAction(nameof(Login));
        }
               
        //隐形使用ajax
        [AcceptVerbs("Get", "Post")]
        public async Task<IActionResult> IsUserName(string UserName)
        {
            var user = await _userManager.FindByNameAsync(UserName);
            if (user == null)
            {
                return Json(true);
            }
            else
            {
                return Json($"用户名：{UserName} 已被注册使用了。");
            }
        }

        #region 注册

        [HttpGet]
        [AllowAnonymous]
        public IActionResult Register()
        {
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]//防止请求伪造
        public async Task<IActionResult> Register(RegisterViewModel registerViewModel)
        {
            _logger.Log(LogLevel.Warning, "注册用户");
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser();
                user.UserName = registerViewModel.UserName;
                if (registerViewModel.IsSupplier)
                {
                    //user.SupplierId = Guid.NewGuid();
                    user.SupplierName = registerViewModel.SupplierName;
                    user.SupplierNo = registerViewModel.SupplierNo;
                }
                var result = await _userManager.CreateAsync(user, registerViewModel.Password);

                string roleName = registerViewModel.IsSupplier ? Consts.Supplier : Consts.Admin;

                IdentityRole identityRole = await _roleManager.FindByNameAsync(roleName);

                IdentityResult identityResult = null;
                if (await _roleManager.RoleExistsAsync(roleName))
                    identityResult = await _userManager.AddToRoleAsync(user, identityRole.Name);
                else
                {
                    ModelState.AddModelError("注册", $"角色 {identityRole.Name} 不存在");
                    return View(registerViewModel);
                }

                if (result.Succeeded && identityResult != null && identityResult.Succeeded)
                {
                    return View(nameof(Login));
                }

                StringBuilder error = new StringBuilder();
                foreach (var item in result.Errors)
                {
                    error.Append(item.Description);
                }
                if (identityResult != null)
                {
                    foreach (var item in identityResult.Errors)
                    {
                        error.Append(item.Description);
                    }
                }

                ModelState.AddModelError("注册", error.ToString());
            }
            return View(registerViewModel);
        }

        #endregion

        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            return RedirectToAction(nameof(Login));
        }

        public IActionResult RoleLists()
        {
            var list = _roleManager.Roles.ToList();
            return View(list);
        }

        [Authorize(Roles = Consts.Admin)]
        public async Task<IActionResult> SupplierUserLists()
        {
            var list = await _userManager.Users.ToListAsync();
            var user = list.FirstOrDefault(s => s.RoleName == Consts.Admin);
            list.Remove(user);
            return View(list);
        }

        [HttpGet]
        public IActionResult Validation()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Validation(ChangePasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.GetUserAsync(User);
                if (user == null)
                {
                    return RedirectToAction(nameof(Login));
                }
                var result = await _userManager.ChangePasswordAsync(user, model.CurrentPasswoed, model.NewPasswoed);
                if (!result.Succeeded)
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError("ModifyPassword", error.Description);
                    }
                    return View();
                }
                //刷新Cookie
                await _signInManager.RefreshSignInAsync(user);
                return View(nameof(ChangePasswordConfirm));
            }
            return View(model);
        }

        public IActionResult ChangePasswordConfirm()
        {
            return View();
        }

        #region 用户增删改

        [HttpGet]
        public async Task<IActionResult> UserEdit(string Id)
        {
            EditUserViewModel model = new EditUserViewModel();
            if (Id != null)
            {
                var user = await _userManager.FindByIdAsync(Id);
                if (user == null)
                {
                    ViewBag.ErrorMessage = $"无法找到ID为 {Id} 的用户信息";
                    return View("NotFound");
                }

                //model.RoleName = user.RoleName;
                //model.SupplierNo = user.SupplierNo;
                model.SupplierName = user.SupplierName;
                model.UserName = user.UserName;
                model.PhoneNumber = user.PhoneNumber;
                model.LockoutEnabled = user.LockoutEnabled;
                model.AccessFailedCount = user.AccessFailedCount;
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> UserEdit(EditUserViewModel edit)
        {
            IdentityResult result;
            if (!string.IsNullOrWhiteSpace(edit.Id))
            {
                var user = await _userManager.FindByIdAsync(edit.Id);
                if (user == null)
                {
                    ViewBag.ErrorMessage = $"无法找到Id为 {edit.Id} 的用户";
                    return View("NotFound");
                }
                ObjectConver(edit, user, false);
                result = await _userManager.UpdateAsync(user);
            }
            else
            {
                ApplicationUser user = new ApplicationUser();
                ObjectConver(edit, user, true);
                result = await _userManager.CreateAsync(user, "123456");
            }
            if (result.Succeeded)
            {
                return RedirectToAction(nameof(SupplierUserLists));
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("EditUser", error.Description);
            }
            return View();
        }

        private static void ObjectConver(EditUserViewModel edit, ApplicationUser user, bool IsAdd)
        {
            if (IsAdd)
            {
                user.RoleName = Consts.Supplier;
                user.SupplierNo = SecurityHelper.GeneratePassword(5).ToUpper();
            }
            user.SupplierName = edit.SupplierName;
            user.UserName = edit.UserName;
            user.PhoneNumber = edit.PhoneNumber;
            user.LockoutEnabled = edit.LockoutEnabled;
            user.AccessFailedCount = edit.AccessFailedCount;
        }

        public async Task<IActionResult> DeleteUser(string Id)
        {
            var user = await _userManager.FindByIdAsync(Id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"无法找到Id为 {Id} 的用户";
                return View("NotFound");
            }
            //如果删除的是当前登录的用户
            bool IsCurrentUser = user.UserName == User.Identity.Name ? true : false;
            var result = await _userManager.DeleteAsync(user);
            if (result.Succeeded)
            {
                if (IsCurrentUser)
                    return RedirectToAction(nameof(Login));
                else
                    return RedirectToAction(nameof(SupplierUserLists));
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError("DeleteUser", error.Description);
            }
            return RedirectToAction(nameof(SupplierUserLists));
        }

        #endregion

        [HttpGet]
        public IActionResult AccessDenied()
        {
            return View();
        }
    }
}
